
$(function(){
	//初始化
	WordTemplate.init();
});


//代码块
var WordTemplate = {
		
		//初始化
		init : function(){
			
			//参考接口文档 : https://blog.csdn.net/lisa890608/article/details/18403593
			//富文本编辑器初始化
			WordTemplate.MyEditor = KindEditor.create('#MyKindeditor', {
				basePath: '/TFUI/libs/ZUI/lib/kindeditor',
				cssPath: '/TFUI/css/common.css', //引入样式
				allowFileManager : true,
				bodyClass : 'article-content'
			});
			
			//获取模板列表
			this.getWordTemplateList();
			
		},
		
		//生成编号
		createTemplateNoForInput : function(){
			$("#templateNo").val("T" +CommonUtil.createDateNo());
		},
		
		//打开保存模板窗口
		openSaveTemplateWindow : function(type){
			
			//若第一次进来 , 没选择模板 , 则保存的按钮为新增模板
			if(!this.currentEidtRecord){
				type = 1;
			}
			
			$("#saveTemplateTitle").html(type == 1? "存为新模板" : "修改模板")
			
			if(type == 1){
				$("#templateName").val("");
				this.createTemplateNoForInput();
				$("#addWordTemplateWindow").removeAttr("templateId")
			}
			
			if(type == 2){
				$("#addWordTemplateWindow").attr("templateId" , this.currentEidtRecord.id + "")
			}
			
			$("#addWordTemplateWindow").modal();
		},
		
		//获取保存模板参数
		getSaveTemplateParams : function(){
			
			var params = {};
			
			params.content = WordTemplate.MyEditor.html();
			params.templateName = $.trim($("#templateName").val());
			params.templateNo = $.trim($("#templateNo").val());
			params.id = $("#addWordTemplateWindow").attr("templateId");
			
			return params;
			
		},
		
		//保存模板
		saveTemplate : function(type){
			
			var params = this.getSaveTemplateParams();
			
			var requestUrl = "/wordTemplate/saveWordTemplate";
			
			ajaxRequestByJSONParams(requestUrl , params , function(rst){
				
				if(rst.code != 200){
					new $.zui.Messager(rst.message, {icon:'times',type: 'danger',placement: 'center',time:'2000'}).show();
					return;
				}
				
				WordTemplate.getWordTemplateList();
				
				new $.zui.Messager(rst.message, {icon:'times',type: 'success',placement: 'center',time:'2000'}).show();
				
				$("#addWordTemplateWindow").modal("hide");
			});
			
		},
		
		//获取模板列表
		getWordTemplateList : function(){
			
			var requestUrl = "/wordTemplate/findWordTemplateList";
			var params = {"pageNum" : 1 , "pageSize" : 100000};
			
			ajaxRequestAsyncByJSONParams(requestUrl , params , function(rst){
				
				var count = rst.data.total;
				
		 		var dataList = rst.data.list;
		 		
		 		var txt = "";
		 		
		 		WordTemplate.dataList = dataList;
		 		
		 		for(var i = 0 ; dataList && i < dataList.length ; i ++){
		 			txt +=WordTemplate.createRecordTxt(dataList[i], i)
		 		}
		 		
		 		$("#wordTemplateRecordDiv").html(txt);
				
			});
			
			
		},
		
		createRecordTxt : function(data , index){
			
			var txt = '<div  style="width:100%;line-height:26px;margin-top:5px;border:1px solid #ccc;" class="wordTemplateRecordDiv">'+
			    '<span onclick="WordTemplate.editTemplate(this , '+index+')" class="col-sm-2" style="width:82%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:bold;cursor:pointer;color:green;" title="'+data.templateName+'">'+data.templateName+'</span>&nbsp;&nbsp;'+
			    '<span  style="width:10%;">'+
			    	'<i  class="icon icon-download" style="cursor:pointer;" onclick="WordTemplate.exportWord('+index+')" title="导出word"></i>&nbsp;'+
				    '<i  class="icon icon-trash" style="cursor:pointer;" onclick="WordTemplate.openDeleteWindow('+index+')" title="删除模板"></i>'+
				'</span>'+
			'</div>';
			
			return txt;
			
		},
		
		//标记模板
		editTemplate : function(tag , index){
			
			$(".wordTemplateRecordDiv").css({"background" : ""});
			
			$(tag).parent("div").css({"background" : "pink"});
			
			//当前编辑对象
	    	this.currentEidtRecord = this.dataList[index];
	    	
	    	var currentEidtRecord = this.currentEidtRecord;
	    	
	    	$("#templateName").val(currentEidtRecord ? currentEidtRecord.templateName : "");
	    	$("#templateNo").val(currentEidtRecord ? currentEidtRecord.templateNo : "");
			
			WordTemplate.MyEditor.html(currentEidtRecord ? currentEidtRecord.content : "");
			
		},
		
		//打开确认删除弹窗
		openDeleteWindow : function(index){
			
			//当前编辑对象
	    	this.currentDeleteRecord = this.dataList[index];
			
	    	$("#deleteTemplateWindow").modal();
		},
		
		//删除模板
		deleteTemplate : function(index){
			
			var currentDeleteRecord = this.currentDeleteRecord;
			
			var requestUrl = "/wordTemplate/deleteWordTemplateById";
			
			var params = {id : currentDeleteRecord.id};
			
			ajaxRequestAsync(requestUrl , params , function(rst){
				
				if(rst.code != 200){
					new $.zui.Messager(rst.message, {icon:'times',type: 'danger',placement: 'center',time:'2000'}).show();
					return;
				}
				
				WordTemplate.getWordTemplateList();
				
				new $.zui.Messager(rst.message, {icon:'times',type: 'success',placement: 'center',time:'2000'}).show();
				
				$("#deleteTemplateWindow").modal("hide");
				
			});
			
		},
		
		//导出word
		exportWord : function(index){
			
			var currentExportRecord = this.dataList[index];
			
			var requestUrl = "/wordTemplate/exportWord";
			
			var params = {id : currentExportRecord.id};
			
		    var xhr = new XMLHttpRequest();
		    
		    xhr.open('POST', requestUrl , true);        // 也可以使用POST方式，根据接口
		    
		    xhr.responseType = "blob";    // 返回类型blob
		    
		    xhr.setRequestHeader('token' , window.localStorage.getItem("token"));
		    
		    xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
		    
		    // 定义请求完成的处理函数，请求前也可以增加加载框/禁用下载按钮逻辑
		    xhr.onload = function () {
		    	
		    	 var blob = this.response;
		    	
		    	//若是json
		    	if(blob.type == "application/json"){
		    		
		    		this.response.text().then(res=>{
		    			var data = JSON.parse(res);
		    			new $.zui.Messager(data.message, {icon:'times',type: 'success',placement: 'center',time:'2000'}).show();
		    		});
		    		
		    		return;
		    	}
		    	else {
		    		
		    		// 转换完成，创建一个a标签用于下载
		            var a = document.createElement('a');
		            a.download = currentExportRecord.templateName + ".docx";
		            a.href = URL.createObjectURL(blob);
		            $("body").append(a);    // 修复firefox中无法触发click
		            a.click();
		            $(a).remove();
		        }
		    	
		    };
		    
		    // 发送ajax请求
		    xhr.send(JSON.stringify(params));
			
		},
		
		//打开选择标签库弹窗
		openChooseInsertLabelWindow : function(){
			
			var requestUrl = "/markLib/findMarkLibList";
			var params = {"pageNum" : 1 , "pageSize" : 100000};
			
			ajaxRequestAsyncByJSONParams(requestUrl , params , function(rst){
				
				var data = rst.data.list;
				
				if(!data || data.length == 0){
					new $.zui.Messager("暂无标签库配置,请先配置!", {icon:'times',type: 'success',placement: 'center',time:'2000'}).show();
					return;
				}
				
				var libNameTxt = "";
				
				var dataMarkInfoMap = {};
				
				for(var i = 0 ; i < data.length ; i++){
					
					var item = data[i];
					
					dataMarkInfoMap[item.id] = item;
					
					libNameTxt +='<option value="'+item.id + ""+'">'+item.libName+'</option>';
				}
				
				WordTemplate.dataMarkInfoMap = dataMarkInfoMap;
				
				$("#libNameSelect").html(libNameTxt).change();
				
				$("#chooseInsertLabelWindow").modal();
			});
			
		},
		
		//改变标签
		changeLibNameSelect : function(){
			
			var id = $("#libNameSelect").val();
			
			var item = WordTemplate.dataMarkInfoMap[id];
			
			var markInfoList = item.markInfoList;
	    	
	    	var txt = "";
	    	
	    	for(var i = 0 ; markInfoList && i < markInfoList.length ; i ++){
	    		
	    		var item = markInfoList[i];
	    		
	    		txt += '<span onclick="WordTemplate.insertLabel(this)" class="label label-primary" style="float:left;margin-left:10px;margin-top:10px;cursor:pointer;" data-toggle="tooltip" title="'+item.valuePath+'">'+item.markName+'</span>';
	    	}
			
	    	$("#detail_markInfoList").html(txt).change();
		},
		
		//插入标签
		insertLabel : function(tag){
			
			var jqItem = $(tag);
			var valuePath = jqItem.attr("title");
			var markName = jqItem.html();
			
			//需要KindEditor==>设置cssPath: '/TFUI/css/common.css', //varLabel 设置了一个居中, 不然图片无法和文字居中
			var txt = '<img class="varLabel" src="/file/downLoadWordPng?valuePath='+valuePath+'&word='+markName+'"/>';
			
			WordTemplate.MyEditor.insertHtml(txt);
			
			$("#chooseInsertLabelWindow").modal("hide");
		}
		
		
		
};